package com.example.common.util;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * valid校验封装
 *
 * @author zjarlin
 * @since 2022/07/19
 */
@Component
public class Valids {
    private static Validator validator;

    /**
     * 校验list增加一列报错信息
     *
     * @param list 列表 入参
     * @return {@link List }<{@link JSONObject }>
     * @author zjarlin
     * @since 2023/04/15
     */
    public static <T> List<JSONObject> validate(List<T> list) {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();

        return list.stream().map(item -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.putAll(JSONObject.parseObject(JSONObject.toJSONString(item)));

            String validMsg = Optional.ofNullable(validator.validate(item))
                .map(violations -> violations.stream().map(violation -> violation.getMessage())
                    .filter(StrUtil::isNotBlank)
                    .collect(Collectors.joining(",")))
                .orElse(null);
            jsonObject.put("validMsg", validMsg);

            return jsonObject;
        }).collect(Collectors.toList());
    }

    @Autowired
    public void setValidator(Validator validator) {
        Valids.validator = validator;
    }

    public <T> String getValidMsg(T t, CharSequence delimiter) {
        final Set<ConstraintViolation<T>> validate = validator.validate(t);
        return validate.stream().map(ConstraintViolation::getMessage)
            .filter(org.apache.commons.lang3.StringUtils::isNotBlank)
            .collect(Collectors.joining(delimiter));
    }
}
